package com.example.good.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.good.entity.User;
import com.example.good.mapper.UserMapper;
import com.example.good.service.IEmailService;
import com.example.good.service.ex.UpdateException;
import com.example.good.service.ex.UserNotFoundException;
import com.example.good.service.ex.VerificationCodeErrorException;
import com.example.good.util.JsonResult;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ses.v20201002.SesClient;
import com.tencentcloudapi.ses.v20201002.models.SendEmailRequest;
import com.tencentcloudapi.ses.v20201002.models.SendEmailResponse;
import com.tencentcloudapi.ses.v20201002.models.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;

@Service
public class EmailServiceImpl implements IEmailService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void sendEmail(Integer uid, String email) throws TencentCloudSDKException {
        User result = userMapper.findByUid(uid);
        if (result == null){
            throw new UserNotFoundException("用户不存在");
        }
        // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
        // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
        Credential cred = new Credential("AKIDQfeNqmRpwmLefRxDCvNYS5RWKsABvNZU", "g5D5g02oJXUBcmeFaeRxCBuMY1D8mAG5");
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("ses.tencentcloudapi.com");
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
        // 实例化一个请求对象,每个接口都会对应一个request对象
        SendEmailRequest req = new SendEmailRequest();
        req.setFromEmailAddress("haiggood@mail.haiggood.com");

        String[] destination1 = {email};
        req.setDestination(destination1);

        Template template1 = new Template();
        template1.setTemplateID(26766L);
        JSONObject object = new JSONObject();
        String username = result.getUsername();
        object.put("name",username.substring(0,2)+"***"+username.substring(username.length()-2));
        Random random = new Random();
        Integer randomI = ((random.nextInt(100000000)*9+1)*1000000);
        String randomNum = randomI.toString().substring(1,7);

        User user = new User();
        user.setUid(result.getUid());
        user.setTemporaryCode(randomNum);
        user.setModifiedUser(result.getUsername());
        user.setModifiedTime(new Date());
        Integer rows = userMapper.updateInfoByUid(user);
        if (rows != 1){
            throw new UpdateException("更新异常");
        }

        object.put("code",randomNum);
        template1.setTemplateData(object.toString());
        req.setTemplate(template1);

        req.setSubject("hggood--邮箱验证");
//        req.setTriggerType(1L);
        // 返回的resp是一个SendEmailResponse的实例，与请求对象对应
        SendEmailResponse resp = client.SendEmail(req);
        // 输出json格式的字符串回包
        System.out.println(SendEmailResponse.toJsonString(resp));
    }

    @Override
    public void checkEmail(Integer uid,String email, String checkNum) {
        User result = userMapper.findByUid(uid);
        if (result == null){
            throw new UserNotFoundException("用户不存在");
        }
        System.out.println(result.getTemporaryCode());
        System.out.println(checkNum);
        if (!checkNum.equals(result.getTemporaryCode())) {
            throw new VerificationCodeErrorException("验证码错误");
        }
        /**如果验证码错误就不会往下执行了*/
        Random random = new Random();
        Integer randomI = ((random.nextInt(100000000)*9+1)*1000000);

        User user = new User();
        user.setUid(result.getUid());
        user.setEmail(email);
        user.setTemporaryCode(randomI.toString().substring(1,7));
        user.setModifiedUser(result.getUsername());
        user.setModifiedTime(new Date());
        Integer rows = userMapper.updateInfoByUid(user);
        if (rows != 1){
            throw new UpdateException("更新异常");
        }
    }
}
